package top.leyi.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import top.leyi.entity.user.User;
import top.leyi.exception.NoSuchAuthException;
import top.leyi.exception.NotSuchUserIdException;
import top.leyi.mapper.UserMapper;

import java.util.List;

/**
 * @desc 使用aop为说说进行权限认证，
 * 1 ： 用户是否存在
 * 2 ： 用户是否具有以下权限
 *
 *     超级用户   id：19  token：4ce2655b261752c951b34429073547a8
 */

//@Configuration
@Aspect
public class UserAuthAop {

    @Autowired
    UserMapper userMapper;

    /**
     * @desc 对于含义参数为user的方法进行拦截
     */
     @Pointcut(value =  "execution(public * top.leyi.IService.ITalkService.*(.., top.leyi.entity.user.User))||" +
                        "execution(public * top.leyi.IService.IActivityService.*(.., top.leyi.entity.user.User))||" +
                        "execution(public * top.leyi.IService.IPushService.addOnePush(.., top.leyi.entity.user.User))||" +
                        "execution(public * top.leyi.IService.IPushService.removePush(.., top.leyi.entity.user.User))||" +
                        "execution(public * top.leyi.IService.ICollectionService.addOneCollection(.., top.leyi.entity.user.User))||" +
                        "execution(public * top.leyi.IService.ICollectionService.removeCollection(.., top.leyi.entity.user.User)) || " +
                        "execution(public * top.leyi.IService.ICommService.addOneCommo(.., top.leyi.entity.user.User)))"
              )
     public void welog(){
     }

    @Around("welog()")
    public Object   doAround(ProceedingJoinPoint jp) throws  NoSuchAuthException, Throwable{

        Object o = null;
        User user = null;

        try{
            user = (User) jp.getArgs()[1];
        }catch (Exception e){
            System.out.println("此方法不需要进入aop");
            jp.proceed(new Object[]{jp.getArgs()});
        }


         // 获取方法名
        String[] signatures = jp.getSignature().toString().split("\\.");
        String operation = signatures[signatures.length - 1].split("\\(")[0];

        user = userMapper.queryOneUserWithToken(user);
        /*
            如果没有这个用户，则抛出异常
         */
        if(user == null){
            throw new NotSuchUserIdException();
        }
        int roleId = userMapper.queryRoleId(user.getId());
        /**
         * @desc 如果此用户不是管理员的话(1)
         */
        if(roleId != 1) {
            List<String> powers = userMapper.queryOwnPrivilege1(roleId);
            boolean flag = false;
            for (String power : powers) {
                if (power.equals(operation)) {
                    flag = true;
                }
            }
            if (!flag) {
                throw new NoSuchAuthException("缺乏权限");
            }
        }

        return jp.proceed(new Object[]{jp.getArgs()[0], user});
    }

}
